<?php

namespace Beerus\Modules\DesignerAdv\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Beerus\Modules\DesignerAdv\Actions\HadUpload;
use Beerus\Modules\DesignerAdv\Actions\PassDesignerList;
use Beerus\Modules\DesignerAdv\Actions\PassMatter;
use Doraemon\cache\Queue;
use Doraemon\cache\UserNick;
use Doraemon\model\KaManage\KaDesignerMatter;
use Doraemon\model\KaManage\KaDesignerPerch;
use Doraemon\model\KaManage\KaMatterOpLog;
use Doraemon\model\KaManage\KaResourcePlace;
use Doraemon\model\Member;
use Doraemon\pockets\config\IniConfig;
use Doraemon\service\KaManage\PerchMatter;
use Doraemon\service\User;
use Doraemon\tools\Curl as DCurl;
use Encore\Admin\Actions\Action;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;

class KaAdvMaterialController extends Controller
{
	const PAGE_SIZE = 20;

	// 搜索结果页可操作性状态
	const ADV_STATUS = [
		KaDesignerMatter::STATUS_NORMAL => '待上传',
		KaDesignerMatter::STATUS_AUDIT => '审核中',
		KaDesignerMatter::STATUS_APPROVE => '审核通过',
		KaDesignerMatter::STATUS_NO_APPROVE => '审核不通过',
		//KaDesignerMatter::STATUS_DELETE => '已删除'
	];

	// 其他资源位可操作状态
	const OTHER_AUDIT_STATUS = [
		KaDesignerMatter::STATUS_NORMAL => '待上传',
		KaDesignerMatter::STATUS_APPROVE => '审核通过',
	];

	public function __construct()
	{
		parent::__construct();
		Admin::script('$(".pjax-container").attr("id","pjax-container");');
	}

	public function index(Request $request, Content $content)
	{
		$request_data = $request->all();
		$page_size = $request->input("per_page", self::PAGE_SIZE);
		$page = $request->input("page", 1);

		$condition = [];
		if (!empty($request_data['uid'])) {
			$condition['uid'] = $request_data['uid'];
		}

		if (!empty($request_data['nick'])) {
			$uid = User::getUidByNick($request_data['nick']);
			$condition['uid'] = $uid;
//			$uids = self::searchByNick($request_data['nick']);
//			if (empty($uids)) {
//				$condition['uid'] = '';
//			} else {
//				$condition['uid'] = $uids;
//			}
		}

		if (!empty($request_data['online_date']['start'])) {
			$condition['perch_date[>=]'] = $request_data['online_date']['start'];
		}

		if (!empty($request_data['online_date']['end'])) {
			$condition['perch_date[<=]'] = $request_data['online_date']['end'];
		}

		if (!empty($request_data['type'])) {
			$condition['type'] = $request_data['type'];
		}

		if (!empty($request_data['data_status'])) {
			$condition['data_status'] = $request_data['data_status'];
		} else {
			$condition['data_status[!]'] = KaDesignerMatter::STATUS_DELETE;
		}

		$condition['ORDER'] = ['perch_date' => 'ASC'];
		$condition['LIMIT'] = [
			($page - 1) * $page_size,
			$page_size
		];

		$lists = KaDesignerMatter::select('*', $condition);

		$total = 0;
		if (!empty($lists)) {
			unset($condition['ORDER']);
			unset($condition['LIMIT']);
			$total = KaDesignerMatter::count($condition);
			$user_ids = array_column($lists, 'uid');
			$member_info = Member::getUsers($user_ids);

			foreach ($lists as &$item) {
				$item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
				$perch_info = KaDesignerPerch::get('*', [
					'uid' => $item['uid'],
					'id' => $item['perch_id'],
					'resource_detail_id' => $item['resource_detail_id'],
				]);
				$resource_place_id = $perch_info['resource_place_id'];

				$place_info = KaResourcePlace::get('*', [
					'id' => $resource_place_id
				]);
				$item['position'] = $place_info['position'];
				$item['city'] = $perch_info['city'];
			}
			unset($item);
		}

		unset($condition['ORDER'], $condition['LIMIT']);

		$gridModel = new pGridDataModel($lists, $total, [
			'perPage' => $page_size
		]);
		$gridList = Admin::grid(
			$gridModel,
			function (Grid $grid) use ($gridModel) {
				$grid->paginate($gridModel->getPerPage());
				$grid->disableExport();
				$grid->disableRowSelector();
				$grid->disableCreateButton();
				$grid->setActionClass(DropdownActions::class);

				$grid->filter(function (Grid\Filter $filter) {
					$filter->disableIdFilter();
					$filter->column(1 / 2, function ($filter) {
						$filter->equal('uid', '用户UID')->placeholder('请输入uid');
					});
					$filter->column(1 / 2, function ($filter) {
						$filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
					});
					$filter->column(1 / 2, function ($filter) {
						$filter->equal('type', '展示位')->select(KaDesignerPerch::RESOURCE_DETAIL_TITLE);
					});
					$filter->column(1 / 2, function ($filter) {
						$filter->equal('data_status', '广告状态')->select(self::ADV_STATUS);
					});
					$filter->column(1 / 2, function ($filter) {
						$filter->between('online_date', '上线时间')->date();
					});

					$filter->expand();
				});

				$grid->column("id", '素材id');
				$grid->column("perch_id", '占位id');
				$grid->column("uid", '用户UID');
				$grid->column('nick', '昵称');
				$grid->column('city', '投放城市');
				$grid->column('type','展示位')->display(function () {
					return KaDesignerPerch::RESOURCE_DETAIL_TITLE[$this->type];
				});
				$grid->column('position', '列表位置');
				$grid->column("perch_date", '上线时间');
				$grid->column("matter_obj", '广告素材')->display(function () {
					$matter = json_decode($this->matter_obj, true);
					$matter_show = [];
					foreach ($matter as $value) {
						$link = $value['obj_link'];
						$title = $value['obj_title'];
						if (!empty($title)) {
							$matter_show[] = "「<a target='_blank' href='$link'>$title</a>」";
						}
					}
					return implode('<br/>', $matter_show);
				});
				$grid->column('data_status','广告状态')->display(function () {
					return self::ADV_STATUS[$this->data_status];
				});
				$grid->column("admin_id", '操作人')->display(function () {
					if (!$this->admin_id) {
						return '-';
					} else {
						return Admin::user()->find($this->admin_id)->name;
					}
				});

				$grid->actions(function (Grid\Displayers\Actions $actions) {
					$actions->disableDelete();
					$actions->disableView();
					if (!in_array($actions->row->data_status, [
						KaDesignerMatter::STATUS_APPROVE,
						KaDesignerMatter::STATUS_DELETE
					])) {
						if ($actions->row->type == KaDesignerPerch::START_SCREEN) {
							$actions->add(new HadUpload);
						} else if($actions->row->type == KaDesignerPerch::DESIGNER_LIST) {
                            $actions->add(new PassDesignerList);
                        } else {
							$actions->add(new PassMatter);
						}
					}
				});
			}
		);

		$tab = new Tab();
		$tab->add('KA广告素材列表', $gridList->render());
		$content->row($tab);
		return $content
			->header('KA广告素材列表')
			->description('支持查询和展示设计师的广告素材')
			->breadcrumb(['text' => 'KA广告素材列表']);
	}

	/**
	 * 新增、修改黑名单
	 * @param Request $request
	 * @param Content $content
	 * @param int $id
	 * @return Content
	 */
	public function edit(Request $request, Content $content, $id = 0)
	{
		$header = '编辑素材信息';
		$tab = new Tab();
		$tab->add('素材详情', self::editAction($id));
		return $content->header($header)
			->breadcrumb([
				'text' => 'KA广告素材列表',
				'url' => route('material.list')
			], ['text' => $header])->row($tab);
	}

	public function editAction($id)
	{
		$matter_info = KaDesignerMatter::get('*', [
			'id' => $id
		]);
		$perch_info = KaDesignerPerch::get('*', [
			'id' => $matter_info['perch_id']
		]);
		$user = Member::getOne($perch_info['uid']);
		$place_info = KaResourcePlace::get('*', [
			'id' => $perch_info['resource_place_id']
		]);

		$data = [
			'id' => $matter_info['id'],
			'uid' => $matter_info['uid'],
			'nick' => $user['nick'],
			'city' => $perch_info['city'],
			'type' => $matter_info['type'],
			'position' => $place_info['position'],
			'perch_date' => $matter_info['perch_date'],
			'matter_obj' => empty($matter_info['matter_obj']) ? [] : json_decode($matter_info['matter_obj'], true),
			'data_status' => $matter_info['data_status'],
			'perch_id' => $matter_info['perch_id'],
			'resource_detail_id' => $matter_info['resource_detail_id'],
			'matter_resource_id' => $matter_info['matter_resource_id']
		];

		$form = new Form($data);
		$form->hidden('id');
		$form->hidden('perch_id');
		$form->hidden('resource_detail_id');
		$form->text('uid', '用户UID')->setWidth(4, 2)->readonly();
		$form->text('nick', '昵称')->setWidth(4, 2)->readonly();
		$form->text('city','投放城市')->help('设计师的服务地区')->readonly();
		$form->select('type','展示位')->options(KaDesignerPerch::RESOURCE_DETAIL_TITLE)->readonly();
		$form->text('position','列表位置')->readonly();
		$form->date('perch_date','上线时间')->readonly();
		$form->table('matter_obj', '广告素材', function ($table) {
			$table->hidden('create_time', '创建时间')->readonly();
			$table->text('obj_id', '素材id')->readonly();
			$table->text('obj_keyword', '素材关键词')
				->help('仅「搜索结果」有该字段');
			$table->text('obj_title', '素材标题')->readonly();
			$table->url('obj_link', '素材链接')->rules('required');
			$table->display('obj_link', '')->with(function ($value) {
				return "<a href='$value' target='_blank'>预览</a>";
			});
			$table->text('obj_type', '素材类型')
				->help("<br/>0代表图片<br/>1代表整屋<br/>5代表文章")
				->readonly();
		});
		$form->text('matter_resource_id','资源位后台的id')->readonly();

		$adv_status = self::OTHER_AUDIT_STATUS;
		if ($data['type'] == KaDesignerPerch::SEARCH_RESULT) {
			$adv_status = self::ADV_STATUS;
		}
		$form->select('data_status','广告状态')->default(KaDesignerMatter::STATUS_NORMAL)
            ->setWidth(4, 2)->options($adv_status);
		$form->disableReset();

		$form->action('/admin/DesignerAdv/material_list/save');

		$script = <<<SCRIPT
$('button[type=submit]').on('click',function(e){
    e.preventDefault();
    var form = $(this).parents('form');
    swal({
        title: "请确认广告素材是否准确，审核通过后将自动同步到资源位管理系统",
        text: "请谨慎操作！",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        preConfirm: function() {
            form.submit();
        }
    });
});
SCRIPT;
		Admin::script($script);

		return $form->render();
	}

	public function save(Request $request)
	{
		$params = $request->all();
		$id = $params['id'];
		
		$matter_info = KaDesignerMatter::get('*', [
			'id' => $id
		]);

		$update_data = [
			'perch_date' => $params['perch_date'],
			'data_status' => $params['data_status'],
		];

		$matter_data = [];
		if (isset($params['matter_obj'])) {
			list($msec, $sec) = explode(' ', microtime());
			$msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
			foreach ($params['matter_obj'] as $item) {
				if ($item['_remove_']) continue;
				unset($item['_remove_']);

				$convert_data = PerchMatter::convertMatter($item['obj_link'], $matter_info['uid']);
				$item['obj_id'] = $convert_data['obj_id'];
				$item['obj_type'] = $convert_data['type'];
				$item['obj_title'] = $convert_data['title'];

				if (empty($item['create_time'])) {
					$item['create_time'] = $msectime + 1;
					$msectime++;
				}

				$matter_data[] = $item;
			}
		}

		$matter_num = count($matter_data);
		if ($params['type'] == KaDesignerPerch::ARTICLE_CASE && $matter_num > 1) {
			$error = new MessageBag([
				'title' => '整屋最多1个素材'
			]);

			return back()->with(compact('error'));
		}

		if ($params['type'] == KaDesignerPerch::SEARCH_RESULT && $matter_num > 5) {
			$error = new MessageBag([
				'title' => '搜搜结果页最多5个素材'
			]);

			return back()->with(compact('error'));
		}

		$update_data['matter_obj'] = json_encode($matter_data);

		$old_data = $new_data = $matter_info;
		$old_data['matter_obj'] = json_decode($matter_info['matter_obj'], true);
		$new_data['perch_date'] = $params['perch_date'];
		$new_data['data_status'] = $params['data_status'];
		$new_data['matter_obj'] = $matter_data;

		KaMatterOpLog::insert([
			'uid' => $params['uid'],
			'matter_id' => $id,
			'old_data' => json_encode($old_data),
			'new_data' => json_encode($new_data),
			'edit_time' => date('Y-m-d H:i:s'),
			'admin_id' => Admin::user()->id
		]);

		KaDesignerMatter::update($update_data, [
			'id' => $id
		]);

		KaDesignerPerch::update([
			'perch_date' => $params['perch_date']
		], [
			'id' => $params['perch_id']
		]);

		// 搜索结果页素材审核通过投队列
		if (in_array((int)$params['type'], [KaDesignerPerch::ARTICLE_CASE, KaDesignerPerch::SEARCH_RESULT, KaDesignerPerch::DESIGNER_LIST])
			&& $params['data_status'] == KaDesignerMatter::STATUS_APPROVE) {
				Queue::insertQueue('queue/Resource/Sync', [
					'perch_id' => $matter_info['perch_id']
				], Queue::QUEUE_DORAEMON);
		}

		$success = new MessageBag([
			'title' => '修改成功'
		]);

		//return redirect('/admin/DesignerAdv/material_list')->with(compact('success'));
		return redirect("/admin/DesignerAdv/material_list/{$id}/edit")->with(compact('success'));
	}

	public function searchByNick($keyword)
	{
		$config = IniConfig::getConfigSelect('search_mod', 'user');
		$path = $config['host'] . "/list";

		$uid =  UserNick::nick2uid($keyword);

		$filter['nick'] = $keyword;
		$filter['nosegment'] = 1;
		$filter['page'] = 1;
		$filter['pagesize'] = 30;
		$data = DCurl::Request("POST", $path, ['form_params'=> $filter]);
		$data = json_decode($data['data'], true);
		$total = $data['data']['total'];
		$uids = $data['data']['rows'];

		if ($uid) {
			$total = $total + 1;
			array_unshift($uids, $uid);
		}

		return $uids;
	}
}
